from flask import Blueprint, request, render_template, g
from ..core import data_flow_diag
from . import get_data, handle_error, params_check
from werkzeug.datastructures import FileStorage
from flask import request, jsonify  # 导入 jsonify
import tempfile
import os
import traceback

data_flow_diag_blueprint = Blueprint('data_flow_diag_blueprint', __name__, url_prefix='/data_flow_diag')


@data_flow_diag_blueprint.before_request
@handle_error
def before_request():
    get_data()


@data_flow_diag_blueprint.route('/mc', methods=['POST'])
def handle():
    # if request.method == 'POST':
    #     print("aaa", request.files.get('file').__class__)
    #     a: FileStorage = request.files.get('file')
    #     b = a.stream.readlines()
    #     return data_flow_diag.getMcCabe(b)
    # else:
    #     return None
    if request.method == 'POST':
        try:
            a: FileStorage = request.files.get('file')
            if not a:
                return jsonify({'error': 'No file uploaded'}), 400

            # 创建临时文件
            with tempfile.NamedTemporaryFile(delete=False, suffix=".dot", mode='wb') as temp_file:
                for line in a.stream.readlines():  # 确保按行写入，且是字符串
                    temp_file.write(line)
                temp_file_path = temp_file.name

            # 调试：读取临时文件内容
            try:
                with open(temp_file_path, 'r') as f:
                    temp_file_content = f.read()
                print(f"Temporary file content:\n{temp_file_content}")
            except Exception as e:
                print(f"Error reading temporary file: {e}")

            # 调用 getMcCabe 函数, 传入临时文件路径
            result = data_flow_diag.getMcCabe(temp_file_path)

            # 删除临时文件
            os.unlink(temp_file_path)

            return result

        except Exception as e:
            error_message = f"Exception Type: {type(e).__name__}\n{traceback.format_exc()}"
            print(error_message)  # 将错误信息打印到控制台
            return jsonify({'error': error_message}), 500
    else:
        return jsonify({'error': 'Method not allowed'}), 405


# 测试用
@data_flow_diag_blueprint.route('/hello')
def hello():
    return {'code': 200, 'data': "success! :)"}
